#include<cstring>
#include<string>
#include<iostream>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>


void usage(std::string proc)
{
    std::cout << proc << "  server_ip  server_port" << std::endl;
}

int main(int argc , char* argv[])
{
    if(argc != 3)
    {
        usage(argv[0]);
        return 1;
    }

    std::string svr_ip = argv[1];
    uint16_t svr_port = (uint16_t)atoi(argv[2]);
    //1.create
    int sock = socket(AF_INET,SOCK_STREAM,0);
    if(sock < 0)
    {
        std::cerr << " socket error" << errno << std::endl;
        return 2;
    }
    // 2. bind 自动

    // 3. connect
    struct sockaddr_in server;
    memset(&server,0,sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(svr_port);
    server.sin_addr.s_addr = inet_addr(svr_ip.c_str());
    if(connect(sock,(struct sockaddr*)&server,sizeof(server)) < 0 )
    {
        std::cerr << " connect error" << errno << std::endl;
        return 3;
    }   

    std::cout << "connect succeed" << std::endl;

    //请求服务 
    char buff[1024];
    while(true)
    {
        //write
        std::cout << "输入##" ;
        std::string message;
        std::cin >> message;
        write(sock,message.c_str(),message.size());

        //read
        memset(buff,0,sizeof buff);
        int s = read(sock,buff,sizeof(buff) - 1);
        buff[s] = 0;
        std::cout << buff << std::endl;
    }

    return 0;
}